var fuseOptions = {
  // shouldSort: true,
  // includeMatches: true,
  // threshold: 0.0,
  // tokenize:true,
  // location: 0,
  // distance: 100,
  // maxPatternLength: 32,
  // minMatchCharLength: 1,
  // keys: [
  //   {name:"title",weight:0.8},
  //   {name:"contents",weight:0.5},
  //   {name:"tags",weight:0.3},
  //   {name:"categories",weight:0.3}
  // ]
  keys: [
    "title",
    "contents",
    "tags",
    "categories"
  ]
};


var searchQuery = param("s");
if(searchQuery){
  $("#search-query").val(searchQuery);
  executeSearch(searchQuery);
}else {
  $('#search-results').append("<p>Please enter a word or phrase above</p>");
}


function executeSearch(searchQuery){
  $.getJSON( "/js/index.json", function( data ) {
    var pages = data;
    var fuse = new Fuse(pages, fuseOptions);
    var result = fuse.search(searchQuery);
    // console.log({"matches":result});
    if (result.length > 0) {
      var txt = '';
      var readmore = $("#readmore").html()
      for (var i = 0; i < result.length; i++) {
        txt += '<div class="blog-item">';
          txt += '<div class="blog-content">';
              txt += '<h2><a href="'+result[i].item.uri+'">'+result[i].item.title+'</a></h2>';
              txt += '<h3>'+result[i].item.contents+'</h3>';
              txt += '<a class="readmore" href="'+result[i].item.uri+'">'+readmore+' <i class="fa fa-long-arrow-right"></i></a>';
          txt += '</div>';
        txt += '</div>';
      }
      $('#search-results').append(txt);
    } else {
      $('#search-results').append("<p>No matches found</p>");
    }
  });
}

function param(name) {
    return decodeURIComponent((location.search.split(name + '=')[1] || '').split('&')[0]).replace(/\+/g, ' ');
}

